package service

import (
	"fmt"
	"harbor/src/cmd"
	"harbor/src/models"
)

func PullAndPushImages(harobrpass models.User,newharborpass models.User,HARBOR_URL string,NewHARBOR_URL string ,image string ) {
	login:=`docker login -u `+harobrpass.UserName+` -p `+harobrpass.Password+` `+HARBOR_URL
	fmt.Println("同步镜像",image)
	if !cmd.CmdExec(login){
		fmt.Println("loginerr")
		fmt.Println(login)
	}
	pullimage:= `docker pull `+HARBOR_URL+`/`+image
	if !cmd.CmdExec(pullimage){
		fmt.Println("pullimageerr")
		fmt.Println(pullimage)
	}
	fmt.Println("pullfinish",image)
	newlogin:=`docker login -u `+newharborpass.UserName+` -p `+newharborpass.Password+` `+NewHARBOR_URL
	if !cmd.CmdExec(newlogin){
		fmt.Println("loginerr")
	}
	newimage:= `docker tag `+HARBOR_URL+`/`+image +` `+NewHARBOR_URL+`/`+image
	if !cmd.CmdExec(newimage){
		fmt.Println("tagerr")
	}
	pushimage:= `docker push `+NewHARBOR_URL+`/`+image
	if !cmd.CmdExec(pushimage){
		fmt.Println("pusherr",image)
	}else{
		fmt.Println("pushfinish\n",image)
	}
	rmimage:= ` docker rmi `+NewHARBOR_URL+`/`+image
	if !cmd.CmdExec(rmimage){
		fmt.Println("pusherr:",rmimage)
	}
	rmimagesec:= ` docker rmi `+HARBOR_URL+`/`+image
	if !cmd.CmdExec(rmimagesec){
		fmt.Println("deletenererr:",rmimagesec)
	}
}

//全量同步
func AllImageSync(NewImages []*models.Image_tag,Images []*models.Image_tag,harobrpass models.User,newharborpass models.User,HARBOR_URL string,NewHARBOR_URL string ) {
	for _,image:=range Images{
		for _,new_image:=range NewImages{
			if image.Name==new_image.Name&&image.Size==new_image.Size&&image.Digest==new_image.Digest{
				continue
			}
			PullAndPushImages(harobrpass,newharborpass,HARBOR_URL,NewHARBOR_URL,image.Name)
		}
	}
}

//推送新旧Harbor的差集
func ExceptImageSync(NewImages []models.Image_tag,Images []models.Image_tag,harobrpass models.User,newharborpass models.User,HARBOR_URL string,NewHARBOR_URL string ) {

	for _,image:= range Images{
		if countimages(NewImages,image)==true{
			PullAndPushImages(harobrpass,newharborpass,HARBOR_URL,NewHARBOR_URL,image.Name)
		//	fmt.Println(image.Name)
		}
	}
}

func countimages(NewImages []models.Image_tag,Images models.Image_tag) bool{
		for i,NewImage:=range NewImages{
			if Images.Name==NewImage.Name{
				return false
			}
			if Images.Name!=NewImage.Name&&i==len(NewImages){
				return true
			}
	}
	return true
}